package com.yt.controller;

import com.yt.dao.StorageDao;
import com.yt.entity.Storage;
import com.yt.util.CommonResult;
import io.seata.core.context.RootContext;
import io.seata.integration.http.XidResource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @Classname StorageController
 * @Description
 * @Date 2021/11/3 10:44
 * @Create by 杨涛
 */
@RestController
@Slf4j
public class StorageController {

    @Resource
    StorageDao storageDao;


    @RequestMapping("/storage/decrease")
    CommonResult decrease(@RequestParam("productId") Long productId
            , @RequestParam("count") Integer count,@RequestParam("xid") String xid) {
        RootContext.bind(xid);
        Storage storage=storageDao.getStorageByPid(productId);
//        storage.getResidue()
        if(storage.getResidue()-count>=0){
            log.info(storage.toString());
            storage.setUsed(storage.getUsed()+count);
            storage.setResidue(storage.getResidue()-count);
            storageDao.updateStorage(storage);
            XidResource.cleanXid(xid);
            return new CommonResult(200,"库存已减少");
        }else{
           throw new RuntimeException("库存不足");
        }
    }
}
